from langchain_community.llms import Tongyi
from langchain import hub
from langchain.agents import AgentExecutor,tool
from langchain.agents.output_parsers import XMLAgentOutputParser

import os

os.environ['LANGCHAIN_API_KEY'] = "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"

llm = Tongyi()


@tool
def serach(query):
    """当需要了解最新天气的时候使用这个工具"""
    return "今天天气很晴朗，22°，适合出去跑路爬山"

tool_list = [serach]

# 定义模板
# https://smith.langchain.com/hub
prompt = hub.pull("hwchase17/xml-agent-convo")
print(prompt)


def convert_intermediate_steps(intermediate_steps):
    log = ""
    for action,observation in intermediate_steps:
        log +=(
            f"<tool>{action.tool}</tool><tool_input>{action.tool_input}</tool_input>"
            f"<observation>{observation}</observation>"
        )
    return log

def convert_tolls(tools):
    return "\n".join([f"{tool.name}:{tool.description}" for tool in tools])



agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: convert_intermediate_steps(
            x["intermediate_steps"]
        ),
    }
    | prompt.partial(tools=convert_tolls(tool_list))
    | llm.bind(stop=["</tool_input>", "</final_answer>"])
    | XMLAgentOutputParser()
)

agent_executor = AgentExecutor(agent=agent, tools=tool_list, verbose=True)
print(agent_executor.invoke({"input": "今天天气怎么样"}))



